<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>数据库表结构对比</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" href="../static/css/style.css">
</head>
<body>
<h1>MySQL 数据库表结构对比工具</h1>

<form action="/compare" method="post">
    <div class="form-container">
        <div style="flex: 1;">
            <div class="database-section">
                <div class="database-title">主库（参考库）</div>
                <div class="form-group">
                    <label for="masterDbUrl">URL:</label>
                    <input type="text" id="masterDbUrl" name="masterDbUrl" th:value="${masterDbUrl}" placeholder="jdbc:mysql://localhost:3306/master_db" required>
                </div>
                <div class="form-group">
                    <label for="masterUsername">用户名:</label>
                    <input type="text" id="masterUsername" name="masterUsername" th:value="${masterUsername}" required>
                </div>
                <div class="form-group">
                    <label for="masterPassword">密码:</label>
                    <input type="password" id="masterPassword" name="masterPassword" th:value="${masterPassword}" required>
                </div>
            </div>
        </div>

        <div style="flex: 1;">
            <div class="database-section">
                <div class="database-title">目标库</div>
                <div class="form-group">
                    <label for="targetDbUrl">URL:</label>
                    <input type="text" id="targetDbUrl" name="targetDbUrl" th:value="${targetDbUrl}" placeholder="jdbc:mysql://localhost:3306/target_db" required>
                </div>
                <div class="form-group">
                    <label for="targetUsername">用户名:</label>
                    <input type="text" id="targetUsername" name="targetUsername" th:value="${targetUsername}" required>
                </div>
                <div class="form-group">
                    <label for="targetPassword">密码:</label>
                    <input type="password" id="targetPassword" name="targetPassword" th:value="${targetPassword}" required>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label for="tableName">表名:</label>
        <input type="text" id="tableName" name="tableName" th:value="${tableName}">
        <span style="font-size: 12px; color: #6c757d; margin-left: 10px;">(留空表示全量对比)</span>
    </div>

    <input type="submit" value="单表对比" name="action">
    <input type="submit" value="全量对比" name="action">
</form>

<!-- 错误信息显示 -->
<div class="result" th:if="${error}">
    <h2 style="color: red;">错误</h2>
    <p th:text="${error}"></p>
</div>

<!-- 全量对比结果 -->
<div class="result" th:if="${fullCompare != null and fullCompare}">
    <h2>全量对比结果</h2>
    <div class="table-diff-summary">
        <p th:if="${hasDifference}" class="diff">发现差异！共有 <span th:text="${differentTables}"></span> 个表存在差异</p>
        <p th:if="${hasDifference != null and !hasDifference}" style="color: green;">所有表结构完全一致！共对比了 <span th:text="${totalTables}"></span> 个表</p>

        <!-- 全量导出按钮 -->
        <div th:if="${hasDifference}" style="margin-top: 10px;">
            <a href="/exportAllSql" class="export-btn">导出所有SQL</a>
        </div>
    </div>

    <div th:if="${hasDifference}">
        <h3>差异详情</h3>
        <div class="diff-table-item" th:each="tableDiff, iterStat : ${tableDifferences}">
            <div class="diff-table-title">
                表名: <span th:text="${tableDiff.tableName}"></span>
                <div style="float: right;">
                    <button class="export-btn" type="button" th:onclick="|toggleColumnDisplay(${iterStat.index}, false)|">只显示差异字段</button>
                    <button class="export-btn" type="button" th:onclick="|toggleColumnDisplay(${iterStat.index}, true)|">显示所有字段</button>
                    <a th:href="@{/exportTableSql(tableName=${tableDiff.tableName})}" class="export-btn" style="margin-left: 10px;">导出表SQL</a>
                </div>
            </div>

            <!-- 处理表缺失的情况 -->
            <div th:if="${tableDiff.get('differenceType') != null}">
                <p class="missing-table" th:text="${tableDiff.message}"></p>
                <div class="table-comparison" style="display: flex; flex-wrap: wrap; gap: 20px;">
                    <div class="table-panel" style="flex: 1; min-width: 300px;">
                        <div class="table-header">
                            主库（参考库）
                            <div class="table-name-comment">
                                <span th:text="${tableDiff.tableName}"></span>
                            </div>
                        </div>
                        <table th:if="${tableDiff.table1 != null}">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型</th>
                                    <th>可空</th>
                                    <th>键</th>
                                    <th>默认值</th>
                                    <th>额外</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 显示所有列 -->
                                <tr th:each="col, colStat : ${tableDiff.table1.columns}">
                                    <td class="key-column" th:text="${col.columnName}"></td>
                                    <td th:text="${col.dataType}"></td>
                                    <td th:text="${col.isNullable ?: 'NULL'}"></td>
                                    <td th:text="${col.columnKey ?: ''}"></td>
                                    <td th:text="${col.defaultValue ?: 'NULL'}"></td>
                                    <td th:text="${col.extra ?: ''}"></td>
                                    <td th:text="${col.columnComment ?: '无'}"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 处理表结构差异的情况 -->
            <div th:if="${tableDiff.get('differenceType') == null}">
                <div class="table-comparison" style="display: flex; flex-wrap: wrap; gap: 20px;">
                    <div class="table-panel" style="flex: 1; min-width: 300px;">
                        <div class="table-header">
                            主库（参考库）
                            <div class="table-name-comment">
                                <span th:text="${tableDiff.tableName}"></span>
                            </div>
                        </div>
                        <table th:id="'table-main-diff-' + ${iterStat.index}">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型</th>
                                    <th>可空</th>
                                    <th>键</th>
                                    <th>默认值</th>
                                    <th>额外</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 只显示差异列 -->
                                <tr th:if="${col.hasDifference}" th:each="col, colStat : ${tableDiff.table1.columns}" th:class="${col.hasDifference}? 'diff-row'">
                                    <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                    <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.isNullable ?: 'NULL'}"
                                        th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                    <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                                </tr>
                            </tbody>
                        </table>

                        <!-- 隐藏的完整表格，用于切换显示 -->
                        <table th:id="'table-main-full-' + ${iterStat.index}" style="display: none;">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型</th>
                                    <th>可空</th>
                                    <th>键</th>
                                    <th>默认值</th>
                                    <th>额外</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:if="${tableDiff.table1 != null}" th:each="col, colStat : ${tableDiff.table1.columns}">
                                    <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                    <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.isNullable ?: 'NULL'}"
                                        th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                    <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="table-panel" style="flex: 1; min-width: 300px;">
                        <div class="table-header">
                            目标库
                            <div class="table-name-comment">
                                <span th:text="${tableDiff.tableName}"></span>
                            </div>
                        </div>
                        <table th:id="'table-target-diff-' + ${iterStat.index}">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型</th>
                                    <th>可空</th>
                                    <th>键</th>
                                    <th>默认值</th>
                                    <th>额外</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 只显示差异列 -->
                                <tr th:if="${col.hasDifference}" th:each="col, colStat : ${tableDiff.table2.columns}" th:class="${col.hasDifference}? 'diff-row'">
                                    <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                    <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.isNullable ?: 'NULL'}"
                                        th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                    <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                                </tr>
                            </tbody>
                        </table>

                        <!-- 隐藏的完整表格，用于切换显示 -->
                        <table th:id="'table-target-full-' + ${iterStat.index}" style="display: none;">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>数据类型</th>
                                    <th>可空</th>
                                    <th>键</th>
                                    <th>默认值</th>
                                    <th>额外</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:if="${tableDiff.table2 != null}" th:each="col, colStat : ${tableDiff.table2.columns}">
                                    <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                    <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.isNullable ?: 'NULL'}"
                                        th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                    <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                    <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 单表对比结果 -->
<div class="result" th:if="${fullCompare != null and !fullCompare} and ${table1 != null and table2 != null}">
    <h2>单表对比结果</h2>
    <p th:if="${hasDifference}" class="diff">发现差异！</p>
    <p th:if="${hasDifference != null and !hasDifference}" style="color: green; font-size: 13px;">表结构完全一致！</p>

    <!-- 添加SQL语句显示和导出部分 -->
    <div class="sql-section" th:if="${hasDifference}">
        <h3>SQL 修改语句</h3>
        <div style="text-align: right; margin-bottom: 10px;">
            <a href="/exportSql" class="export-btn">导出SQL文件</a>
        </div>
        <div class="sql-content" th:if="${alterSqlStatements}">
            <div th:each="sql : ${alterSqlStatements}" th:text="${sql}"></div>
        </div>
    </div>

    <h3>表结构详情</h3>
    <div class="table-structure-section">
        <div style="text-align: right; margin-bottom: 10px;">
            <button type="button" class="export-btn" onclick="toggleSingleTableColumnDisplay(false)">只显示差异字段</button>
            <button type="button" class="export-btn" onclick="toggleSingleTableColumnDisplay(true)">显示所有字段</button>
        </div>
        <div id="single-table-details">
            <div class="table-comparison" style="display: flex; flex-wrap: wrap; gap: 20px;">
                <div class="table-panel" style="flex: 1; min-width: 300px;">
                    <div class="table-header">
                        主库（参考库）
                        <div class="table-name-comment">
                            <span th:text="${table1.tableName}"></span>
                        </div>
                    </div>
                    <table id="table1-diff">
                        <thead>
                            <tr>
                                <th>列名</th>
                                <th>数据类型</th>
                                <th>可空</th>
                                <th>键</th>
                                <th>默认值</th>
                                <th>额外</th>
                                <th>注释</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 只显示差异列 -->
                            <tr th:if="${col.hasDifference}" th:each="col, colStat : ${table1.columns}" th:class="${col.hasDifference}? 'diff-row'">
                                <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                <td th:text="${col.isNullable ?: 'NULL'}"
                                    th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                            </tr>
                        </tbody>
                    </table>

                    <!-- 隐藏的完整表格 -->
                    <table id="table1-full" style="display: none;">
                        <thead>
                            <tr>
                                <th>列名</th>
                                <th>数据类型</th>
                                <th>可空</th>
                                <th>键</th>
                                <th>默认值</th>
                                <th>额外</th>
                                <th>注释</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 显示所有列 -->
                            <tr th:each="col, colStat : ${table1.columns}">
                                <td class="key-column" th:text="${col.columnName}"></td>
                                <td th:text="${col.dataType}"></td>
                                <td th:text="${col.isNullable ?: 'NULL'}"></td>
                                <td th:text="${col.columnKey ?: ''}"></td>
                                <td th:text="${col.defaultValue ?: 'NULL'}"></td>
                                <td th:text="${col.extra ?: ''}"></td>
                                <td th:text="${col.columnComment ?: '无'}"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="table-panel" style="flex: 1; min-width: 300px;">
                    <div class="table-header">
                        目标库
                        <div class="table-name-comment">
                            <span th:text="${table2.tableName}"></span>
                        </div>
                    </div>
                    <table id="table2-diff">
                        <thead>
                            <tr>
                                <th>列名</th>
                                <th>数据类型</th>
                                <th>可空</th>
                                <th>键</th>
                                <th>默认值</th>
                                <th>额外</th>
                                <th>注释</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 只显示差异列 -->
                            <tr th:if="${col.hasDifference}" th:each="col, colStat : ${table2.columns}" th:class="${col.hasDifference}? 'diff-row'">
                                <td class="key-column" th:text="${col.columnName}" th:classappend="${col.hasDifference}? 'missing-column'"></td>
                                <td th:text="${col.dataType}" th:classappend="${col.dataTypeDiff}? 'cell-diff'"></td>
                                <td th:text="${col.isNullable ?: 'NULL'}"
                                    th:classappend="${col.isNullableDiff}? 'cell-diff' + ' ' + (${col.isNullable == 'NO' || col.isNullable == 'false'} ? 'nullable-no' : 'nullable-yes')"></td>
                                <td th:text="${col.columnKey ?: ''}" th:classappend="${col.columnKeyDiff}? 'cell-diff'"></td>
                                <td th:text="${col.defaultValue ?: 'NULL'}" th:classappend="${col.defaultValueDiff}? 'cell-diff'"></td>
                                <td th:text="${col.extra ?: ''}" th:classappend="${col.extraDiff}? 'cell-diff'"></td>
                                <td th:text="${col.columnComment ?: '无'}" th:classappend="${col.columnCommentDiff}? 'cell-diff'"></td>
                            </tr>
                        </tbody>
                    </table>

                    <!-- 隐藏的完整表格 -->
                    <table id="table2-full" style="display: none;">
                        <thead>
                            <tr>
                                <th>列名</th>
                                <th>数据类型</th>
                                <th>可空</th>
                                <th>键</th>
                                <th>默认值</th>
                                <th>额外</th>
                                <th>注释</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 显示所有列 -->
                            <tr th:each="col, colStat : ${table2.columns}">
                                <td class="key-column" th:text="${col.columnName}"></td>
                                <td th:text="${col.dataType}"></td>
                                <td th:text="${col.isNullable ?: 'NULL'}"></td>
                                <td th:text="${col.columnKey ?: ''}"></td>
                                <td th:text="${col.defaultValue ?: 'NULL'}"></td>
                                <td th:text="${col.extra ?: ''}"></td>
                                <td th:text="${col.columnComment ?: '无'}"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 保留密码字段的值
    document.addEventListener('DOMContentLoaded', function() {
        // 从 sessionStorage 中恢复密码值
        const masterPassword = sessionStorage.getItem('masterPassword');
        const targetPassword = sessionStorage.getItem('targetPassword');

        if (masterPassword) {
            document.getElementById('masterPassword').value = masterPassword;
        }

        if (targetPassword) {
            document.getElementById('targetPassword').value = targetPassword;
        }

        // 表单提交前保存密码值到 sessionStorage
        const form = document.querySelector('form');
        form.addEventListener('submit', function() {
            sessionStorage.setItem('masterPassword', document.getElementById('masterPassword').value);
            sessionStorage.setItem('targetPassword', document.getElementById('targetPassword').value);
        });
    });

    // 切换列显示模式（全量对比）
    function toggleColumnDisplay(index, showAll) {
        const mainDiff = document.getElementById(`table-main-diff-${index}`);
        const mainFull = document.getElementById(`table-main-full-${index}`);
        const targetDiff = document.getElementById(`table-target-diff-${index}`);
        const targetFull = document.getElementById(`table-target-full-${index}`);

        // 检查元素是否存在
        if (!mainDiff || !mainFull || !targetDiff || !targetFull) {
            console.log("Element not found for index: " + index);
            return;
        }

        if (showAll) {
            // 显示完整表格，但仍需要高亮显示差异字段
            mainDiff.style.display = 'none';
            mainFull.style.display = '';
            targetDiff.style.display = 'none';
            targetFull.style.display = '';

            // 为完整表格中的差异字段添加高亮样式
            highlightDiffRows(mainFull);
            highlightDiffRows(targetFull);
        } else {
            // 显示差异表格
            mainDiff.style.display = '';
            mainFull.style.display = 'none';
            targetDiff.style.display = '';
            targetFull.style.display = 'none';
        }
    }

    // 切换单表列显示模式
    function toggleSingleTableColumnDisplay(showAll) {
        const table1Diff = document.getElementById('table1-diff');
        const table1Full = document.getElementById('table1-full');
        const table2Diff = document.getElementById('table2-diff');
        const table2Full = document.getElementById('table2-full');

        // 检查元素是否存在
        if (!table1Diff || !table1Full || !table2Diff || !table2Full) {
            console.log("Single table element not found");
            return;
        }

        if (showAll) {
            // 显示完整表格，但仍需要高亮显示差异字段
            table1Diff.style.display = 'none';
            table1Full.style.display = '';
            table2Diff.style.display = 'none';
            table2Full.style.display = '';

            // 为完整表格中的差异字段添加高亮样式
            highlightDiffRows(table1Full);
            highlightDiffRows(table2Full);
        } else {
            // 显示差异表格
            table1Diff.style.display = '';
            table1Full.style.display = 'none';
            table2Diff.style.display = '';
            table2Full.style.display = 'none';
        }
    }

    // 为表格中的差异行添加高亮样式
    function highlightDiffRows(table) {
        const rows = table.querySelectorAll('tbody tr');
        rows.forEach(row => {
            // 检查单元格是否有cell-diff类
            const cells = row.querySelectorAll('td');
            let hasDiff = false;
            cells.forEach(cell => {
                if (cell.classList.contains('cell-diff')) {
                    hasDiff = true;
                }
            });

            // 如果有差异单元格，为行添加高亮类
            if (hasDiff) {
                row.classList.add('diff-row');
            }
        });
    }
</script>
</body>
</html>